package think.in.spring.bean.builder;

import org.springframework.beans.factory.config.AutowireCapableBeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import think.in.spring.ioc.overview.domain.User;

/**
 * Bean初始化的3种方法
 * 1. 静态工厂方法
 * 在配置中class配置静态工厂类名，factory-method配置返回对象实例的方法
 *
 */
public class BeanInstanceDemo {
    public static void main(String[] args) throws Exception {
        ApplicationContext context = new ClassPathXmlApplicationContext(
                "classpath:META-INF/BeanDefinition.xml");
        staticMethod(context);
        factoryBean(context);
        beanFactory(context);
        autowrite(context);
    }

    /**
     * 通过静态工厂方法
     * @param context
     */
    public static void staticMethod(ApplicationContext context) {
        User user = context.getBean("static-init-user", User.class);
        System.out.println("static-init-user:"+user);
        Integer int1 = context.getBean("static-init-integer",Integer.class);
        System.out.println("static-init-integer:"+int1);
    }

    /**
     * 通过工厂方法
     * @param context
     */
    private static void factoryBean(ApplicationContext context) {
        User user = context.getBean("userByBeanFactory", User.class);
        System.out.println("userByFactoryBean:"+user);
    }


    public static void beanFactory(ApplicationContext context) throws Exception {
        User user = context.getBean("userByFactoryBean", User.class);
        System.out.println("userFactory:"+user);
    }

    private static void autowrite(ApplicationContext context) {
        AutowireCapableBeanFactory autowireCapableBeanFactory = context.getAutowireCapableBeanFactory();
        User bean = autowireCapableBeanFactory.getBean("static-init-user", User.class);
        System.out.println(bean);
        User bean1 = autowireCapableBeanFactory.createBean(User.class);
        System.out.println(bean1);
    }
}
